<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="wrap">
    <main class="panel-center">
      <div v-show="!viewExperiment" class="tool-bar">
        <ToolBar />
      </div>
      <div v-if="viewVersion" class="mind-history-tip">
        <div class="mind-tip-text">您在正浏览一个历史版本
          <a href="javascript:" @click="quitVersionView()">点击退出</a>
        </div>
      </div>
      <div></div>
      <el-card v-if="viewExperiment && experimentsStatesLoading" class="experiments-states">
        <span v-if="experimentsStatesLoading === 'loading'">
          <svg-icon :icon-class="operatorStatusIcon['Running']" class="Running" />实验数据加载中...
        </span>
        <span v-else>
          <svg-icon :icon-class="operatorStatusIcon[experimentState]" :class="store.experimentState" />实验{{
            instancesStateText[experimentState] }}
        </span>
        <span v-if="store.experimentData.run_time" class="run-time">
          <svg-icon icon-class="shijian" /> {{ store.experimentData.run_time }}
        </span>
      </el-card>
      <el-card v-if="!viewExperiment && store.instanceState" class="experiments-states run-states"
        @click="rightDrawerOpen()">
        <span>
          <svg-icon class="iconSize" :icon-class="operatorStatusIcon[store.instanceState]" :class="store.instanceState" />工作流{{
            instancesStateText[store.instanceState] }}
        </span>
        <span v-if="store.instancesRunData.run_time" class="run-time">
          <svg-icon icon-class="shijian" /> {{ store.instancesRunData.run_time }}
        </span>
      </el-card>
      <div class="x6-graph-box " :class="{ 'readonly': viewExperiment }">
        <div id="x6-graph-container" class="x6-graph-container" />
      </div>
      <canvas-handler />
    </main>
  </div>
</template>

<script setup lang="ts">
import ToolBar from './components/ToolBar/index.vue'
import '@antv/x6-vue-shape'
import CanvasHandler from 'src/pages/designerTool/canvas/DagEdit/components/CanvasHandler/index.vue'
import { ref, onMounted, nextTick, computed, watch, onUnmounted } from "vue"
import { designerStore } from 'src/stores/designerTool/designerTool'
import Mousetrap from 'mousetrap'
import { debounce } from 'throttle-debounce'
import { ports } from 'src/pages/designerTool/canvas/DagEdit/graph/methods'
import { clearPending } from 'src/utils/designerTool/cancelToken'
import {instancesStateText, operatorStatusIcon } from 'src/utils/designerTool/constants'
import dagGraph from 'src/pages/designerTool/canvas/DagEdit/graph/index.js'
import { getWorkflowsDetail } from 'src/api/designerTool'
const store = designerStore()
const debounceFunc = () => {
  debounce(100, () => updateNodePopover())
}
const experimentsStatesLoading = ref('')
const timingExperimentsStates = ref()
const viewVisible = ref(true)
const viewVersion = computed(() => { return !!store.versionId })
const viewExperiment = computed(() => { return !store.LeftTabsState })
const readonly = computed(() => { return viewVersion.value || viewExperiment.value })
function setEventsValue(obj: object) {
  store.SET_PUBLISH_EVENT(obj)
}
function setNodePopover(bool: boolean) {
  store.SET_NODE_POPOVER(bool)
}

onMounted(() => {
  initDagGraph()
  window.addEventListener('message', function (e) {
    const { cmd } = e.data
    if (cmd === 'viewResize') {
      viewResize()
    }
  }, false)
  nextTick(() => {
    if (store.LeftTabsState == false) {
      setTimeout(() => {
        resetEvent()
      }, 100)
    }
  })
})
// watch(() => store.versionId, (newData, oldData) => {
//   resetEvent()
// })
// 刷新画布
watch(() => store.events.resetEvent.index, (newData, oldData) => {
  resetEvent()
})
// 初始化监听事件
watch(() => store.events.initEvent.index, (newData, oldData) => {
  initEvent()
})
// 页面大小发生变化
watch(() => store.events.viewResize.index, (newData, oldData) => {
  viewResize()
})
watch(() => store.events.loadWorkflowInfo.index, (newData, oldData) => {
  getWorkflowInfo()
})

onUnmounted(() => {
  dagGraph.destroy()
  viewVisible.value = false
})
watch(() => store.leftPanel, (newData, olddata) => {
  setTimeout(() => {
    viewResize()
  }, 200)
})
function initDagGraph() {
  dagGraph.init('#x6-graph-container', readonly.value)
  viewResize()
  nextTick(() => {
    store.SET_PUBLISH_EVENT({
      key: 'initEvent',
      data: 'init'
    })
  })
}
const emits = defineEmits(['editorGraphWidth'])
function viewResize() {
  const leftContainer = 230
  let graphWidth = document.body.clientWidth
  let graphHeight = document.body.clientHeight
  if (!viewExperiment.value) {
    if (store.leftPanel) {
      graphWidth -= leftContainer
    }
    graphHeight -= 36
  }
  nextTick(() => {
    dagGraph.graph?.resize(graphWidth, graphHeight)
  })
  let boxSizeObj = {
    width: graphWidth,
    height: graphHeight
  }
  emits('editorGraphWidth', boxSizeObj)
  dagGraph.zoomGraphRealSize()
}


function updateNodePopover() {
  setNodePopover(false)
  setTimeout(() => {
    setNodePopover(true)
  }, 100)
}
// 初始化点击事件
function initEvent() {
  dagGraph.graph?.on('blank:click', (node) => {
    store.SET_SELECTED_ID('')
  })
  dagGraph.graph?.on('node:click', ({ cell }) => {
    store.SET_RIGHT_DRAWER(true)
    isNodeGroup(cell)
  })
  // dagGraph.graph?.on('node:mouseenter', (data) => {
  //   console.log('进入')
  //   console.log(data)
  // })
  // dagGraph.graph?.on('node:mouseleave', ({ cell }) => {
  //   console.log('离开')
  // })
  dagGraph.graph?.on('node:move', ({ cell }) => {
    store.SET_NODE_POPOVER(false)
    isNodeGroup(cell)
  })
  dagGraph.graph?.on('node:moved', ({ cell }) => {
    store.SET_NODE_POPOVER(undefined)
  })
  dagGraph.graph?.on('node:mousedown', ({ cell }) => {
    store.SET_NODE_POPOVER(false)
  })
  dagGraph.graph?.on('node:mouseup', ({ cell }) => {
    store.SET_NODE_POPOVER(undefined)
  })
  dagGraph.graph?.on('scale', () => {
    debounceFunc()
  })
  dagGraph.graph?.on('resize', () => {
    debounceFunc()
  })
  dagGraph.graph?.on('translate', () => {
    debounceFunc()
  })
  if (!readonly.value) {
    // 节点添加删除的监听
    dagGraph.graph?.on('node:added', ({ node }) => {
      store.SET_SELECTED_ID(node.id)
      dagGraph.graph?.resetSelection(node)
    })
    dagGraph.graph?.on('node:removed', ({ node }) => {
      store.SET_SELECTED_ID('')
    })
  }
}
function isNodeGroup(cell: any) {
  if (!dagGraph.graph?.isSelected(cell)) {
    cleanSelection()
    dagGraph.graph?.select(cell.id)
  }
  store.SET_SELECTED_ID(cell.id)
}
function cleanSelection() {
  dagGraph.graph?.cleanSelection()
  store.SET_SELECTED_ID('')
}

function resetEvent() {
  // 重置所有快捷键
  Mousetrap.reset()
  // 停止所有请求
  clearPending()
  // 重置所有参数
  store.resetDataByReadonly()
  // 初始化数据
  dagGraph.init('#x6-graph-container', viewVersion.value)
  store.SET_PUBLISH_EVENT({
    key: 'initEvent',
    data: 'init'
  })
  getWorkflowInfo(store.versionId || undefined, viewVersion.value ? 'readonly' : undefined)
}
function getParam() {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
function getDetailData() {
  let workflowId = store.workflow_id
  if (parseInt(store.versionId) > 0) {
    workflowId = parseInt(store.versionId)
  }

  if (store.LeftTabsState == false && store.experiments_id.workflow_id > 0) {
    workflowId = store.experiments_id.workflow_id
  }
  getWorkflowsDetail(store.project_id, workflowId).then((res: any) => {
    store.SET_WORKFLOW_INFO(res.data)
    const categoriesSubset = store.categoriesSubset
    let {...dag}=JSON.parse(res.data.dag)
    if (dag && dag.cells && Array.isArray(dag.cells) && dag.cells.length) {
      // 还原链接桩
      dag.cells.forEach((row: any) => {
        if (row.shape === 'vue-shape' && row.component === 'algo-node') {
          row.ports['groups'] = ports.groups
          Object.keys(categoriesSubset).forEach(key => {
            if (row.data.id == categoriesSubset[key].id) {
              // row.data = categoriesSubset[key]
              row.data.status = 'Scheduled'
            }
          })
        }
      })
      // 装载流程图数据
      dagGraph.initGraphShape(dag)
      dagGraph.zoomGraphRealSize()
    }
    // if (res.data.id) {
    //   store.SET_INSTANCE_ID(res.data.id)
    //   store.SET_PUBLISH_EVENT({
    //     key: 'initInstancesRunInfo',
    //     data: 'init'
    //   })
    // }
  }).catch(error => {
    console.log(error)
  })
}
// reduction用于覆盖
// readonly只读数据
function getWorkflowInfo(id: any, type = '') {
  let workflowId = ''
  if (type === 'readonly') {
    workflowId = id
  } else if (store.workflow_id) {
    workflowId = (store.workflow_id).toString()
  } else if (store.experimentId) {
    workflowId = store.experimentId
  } else if (store.flowReadonlyId) {
    workflowId = store.flowReadonlyId
  }
  if (!workflowId) {
    getWorkflowInfoError()
    return
  }
  store.SET_CANVAS_LOADING(true)
  getDetailData()
}
function getWorkflowInfoError() {
  console.log('请求错误，重新获取')
}
function quitVersionView() {
  store.SET_VERSION_ID('')
  store.SET_PUBLISH_EVENT({
    key: 'setLeftTabCanvas',
    data: 'init'
  })
}

</script>

<style lang="scss" scoped>
@import "src/css/designerStyles/index.scss";
@import "./index.scss";

::v-deep .el-card__body {
  padding: 10px;
}
.iconSize{
  transform: scale(1.2);
}
</style>
